$(function () {
    $('#comment').on('click', add_comment);
    $('#more-comments-btn').on('click', more_comments);
    
    function add_comment (){
        var btn = $(this),
            cmt = $('#comment-text'),
            cmtLists = $('#comment-lists');      
            
        if ( ! cmt.val() )     {
            return false;
        }
    
        $.ajax({
            type: 'post',
            data: {
                'post_id': btn.attr('post-id'),
                'content': cmt.val()
            },
            beforeSend: function () {
                showLoading(btn);
            },
            url: '/comment/add',
            success: function () {
                $('#loading').hide();
                cmtLists.prepend($(cmtLists.children()[0]).clone().html(cmt.val()));
                cmt.val('');
                hideLoading(btn);
            }
        });
    };
    
    function showLoading(btn) {
        btn.addClass('loading');
    }
    
    function hideLoading(btn) {
        btn.removeClass('loading');
    }
    
    function more_comments() {
        
        var cmdLists = $('#comment-lists'),
            postId   = $(this).attr('post-id'),
            offset   = $('#comment-lists li').length,
            btn      = $(this);
    
        $.ajax({
            type: 'post',
            data: {
                offset: offset,
                post_id: postId
            },
            beforeSend: function () {
                showLoading(btn);
            },
            url: '/comment/more',
            success: function (res) {
                var data = eval('(' + res + ')'),
                    containerMoreComments = 'containner-comment-'+ postId+ offset;
                cmdLists.append('<div style="display: none" id="'+ containerMoreComments +'">'+ data.html+ '</div>');
                $('#'+ containerMoreComments).slideDown(200);
                if ( ! data.hasMoreComments ) {
                    $('#more-comments-btn').hide();
                }
                
                hideLoading(btn);
            }
        });
    }
});